指標與結構體(常見模式)
typedef struct {
int id;
char *name;
} Person;
Person *new_person(const char *name) {
Person *p = malloc(sizeof *p); // 分配 Person
if (!p) return NULL;
p->id = 0;
p->name = malloc(strlen(name) + 1); // 為 name 分配空間
if (!p->name) { free(p); return NULL; }
strcpy(p->name, name);
return p;
}
void free_person(Person *p) {
free(p->name);
free(p);
}
realloc 範例(動態成長陣列)
int *arr = malloc(init_n * sizeof arr);
/ 用到某程度想擴充 */
int *tmp = realloc(arr, new_n * sizeof *arr);
if (tmp == NULL) {
// realloc 失敗:arr 仍指向原來的塊(不可直接丟掉)
// 必須保留 arr,或處理錯誤
} else {
arr = tmp; // 成功則更新指標
}